package JavaBean.model2.web;

import JavaBean.model2.domain.RegisterFormBean;
import JavaBean.model2.domain.UserBean;
import JavaBean.model2.util.DBUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;

@WebServlet(name = "ControllerServlet", urlPatterns = "/ControllerServlet")
public class ControllerServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Content-type", "text/html;charset=GBK");
        response.setCharacterEncoding("GBK");
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String password2 = request.getParameter("password2");
        String email = request.getParameter("email");
        RegisterFormBean formBean = new RegisterFormBean();
        formBean.setName(name);
        formBean.setPassword(password);
        formBean.setPassword2(password2);
        formBean.setEmail(email);

        if (!formBean.validate()) {
            request.setAttribute("formBean", formBean);
            request.getRequestDispatcher("/register.jsp")
                    .forward(request, response);
            return;
        }

        UserBean userBean = new UserBean();
        userBean.setName(name);
        userBean.setPassword(password);
        userBean.setEmail(email);
        boolean b = DBUtil.getInstance().insertUser(userBean);

        if (!b) {
            request.setAttribute("DBMes", "你注册的用户已存在");
            request.setAttribute("formBean", formBean);
            request.getRequestDispatcher("/register.jsp")
                    .forward(request, response);
            return;
        }
        response.getWriter().print("恭喜你，注册成功！三秒后自动跳转");
        request.getSession().setAttribute("userBean", userBean);
        response.setHeader("refresh", "3,url=loginSuccess.jsp");
    }
}
